package com.humble.humbleojjudgeservice.judge.codeSandbox.impl;/*
  humble keep gonging
*/


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.humble.humbleojcommon.common.ErrorCode;
import com.humble.humbleojcommon.exception.BusinessException;
import com.humble.humbleojcommon.utils.MD5Util;
import com.humble.humbleojjudgeservice.judge.codeSandbox.Sandbox;
import com.humble.humbleojmodel.model.codeSandbox.ExecuteCodeRequest;
import com.humble.humbleojmodel.model.codeSandbox.ExecuteCodeResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class RemoteSandbox implements Sandbox {
    @Value("${codeSandbox.remote-ip}")
    private String remoteIp;

    private final static String HUMBLE_SANDBOX_KEY = "28364394";
    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest request) throws Exception {
        String url = "http://"+remoteIp+":8111/executeCode";
        String json = JSONUtil.toJsonStr(request);
        String response = null;
        try {
            response = HttpUtil.createPost(url).body(json).header("secret", MD5Util.strToMD5(HUMBLE_SANDBOX_KEY)).execute().body();
        } catch (Exception e) {
            log.error("連接代碼沙箱出現異常");
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"連接代碼沙箱出現異常");
        }
        if(response==null){
            return null;
        }
        ExecuteCodeResponse bean = JSONUtil.toBean(response, ExecuteCodeResponse.class);
        return bean;

    }
}
